package com.example.controller;

import com.alibaba.fastjson.JSONArray;
import com.example.mapper.AlarmMapper;
import com.example.mapper.FileMapper;
import com.example.mapper.PointEqipmentMapper;
import com.example.mapper.infoMapper;
import com.example.pojo.RuleExcelDev;
import com.example.pojo.RuleExcelUser;
import com.example.pojo.SeRuleFile;
import com.example.pojo.dev.*;
import com.example.pojo.msgDevice;
import com.example.resule.Result;
import com.example.service.FileService;
import com.example.util.ReadExcelRuleEngine;
import com.example.websocket.WebSocketServerCamera;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/drools")
public class ReadExcelRuleEngineController {

    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private PointEqipmentMapper pointEqipmentMapper;
    @Autowired
    private FileService fileService;
    @Value("${web.upload}")
    private String upload;


    @Autowired
    private infoMapper infoMapper;
    @Autowired
    private AlarmMapper alarmMapper;

    private void run() {
        droolsrun droolsrun = new droolsrun();
        Thread thread = new Thread(droolsrun);
        thread.start();

    }
//
//    @GetMapping("/rerule")
//    public String excelUser() {
//        ReadExcelRuleEngine obj = new ReadExcelRuleEngine();
//        File file = new File("E:/2.1_Work/1_Codes/5_RuleEngine/origin.xls");
//        List<RuleExcelDev> ruleExcelDevList;
//        try {
//            ruleExcelDevList = obj.readNormExcel(file);
//        } catch (Exception e) {
//            return "请检查Excel是否为97-2003后缀为.xls文件。";
//        }
//        if (ruleExcelDevList == null || ruleExcelDevList.size() < 1) {
//            return "Excel读取有误";
//        }
//        System.out.println("逆转义Excel读取完毕");
//        obj.writeUserExcel("E:/2.1_Work/1_Codes/5_RuleEngine/out.xlsx", ruleExcelDevList);
//        System.out.println("逆转义Excel写入完毕");
//        return "逆转义完成";
//    }

    @ApiOperation(value = "搜索规则", notes = "测试用接口", httpMethod = "POST")
    @PostMapping(value = "/selectdrools")
    public Result selectdrools(@RequestParam("keyword") String keyword, @RequestParam("monitorType") String monitorType, @RequestParam("whetherUse") String whetherUse) {
        //List<SeRuleFile> selectbykeyword = fileMapper.selectbykeyword(keyword, whetherUse, monitorType);
        List<SeRuleFile> seRuleFiles = fileMapper.selectByType(whetherUse, monitorType);
//        List<SeRuleFile> seRuleFiles1 = fileMapper.selectruntimeByType(whetherUse, monitorType);
        ArrayList<RuleExcelUser> turnclass = turnclass(seRuleFiles, upload, keyword);
//        ArrayList<RuleExcelUser> turnclass1 =  turnclass(seRuleFiles1, uploadRuntime, keyword);
//        if (turnclass1!=null){
//            turnclass.addAll(turnclass1);
//        }


        List<RuleExcelUser> merge = merge(turnclass);
        return Result.success(merge);
    }

    //将execl转为对象
    public ArrayList<RuleExcelUser> turnclass(List<SeRuleFile> seRuleFiles, String upload, String keyword) {
        List<SeRuleFile> selectbykeyword = new ArrayList<>();
        if (null != keyword && keyword != "") {
            for (SeRuleFile seRuleFile : seRuleFiles) {
                if (seRuleFile.getFilename().contains(keyword)) {
                    selectbykeyword.add(seRuleFile);
                }
            }
        } else {
            selectbykeyword = seRuleFiles;
        }

        ReadExcelRuleEngine obj = new ReadExcelRuleEngine();
        ArrayList<RuleExcelUser> ruleExcelUsers = new ArrayList<>();
        //循环查找xls 转为对象
        //Map<String , RuleExcelUser> map_kv = new HashMap<>();
        for (SeRuleFile seRuleFile : selectbykeyword) {
            RuleExcelUser ruleExcelUser = new RuleExcelUser();
            //拆分文件名
            //   String[] split = seRuleFile.getFilename().split("&&");
            //监控对象
            ruleExcelUser.setPointName(seRuleFile.getFilename());
            ruleExcelUser.setModelId(seRuleFile.getModelId());
            //  ruleExcelUser.setDroolsname(seRuleFile.getDroolsname());
            //标准
            ruleExcelUser.setStandard(seRuleFile.getStandard());
            ruleExcelUser.setMonitorType(seRuleFile.getMonitorType());
            ruleExcelUser.setWhethermatches(seRuleFile.getWhethermatches());
            ruleExcelUser.setAlarmType(seRuleFile.getAlarmType());
            ruleExcelUser.setUnit(seRuleFile.getUnit());
            ruleExcelUser.setDbId(seRuleFile.getDbid());
            ruleExcelUser.setUrl(seRuleFile.getUrl());

            List<RuleExcelUser> ruleExcelUserList = new ArrayList<>();
            File file = null;
            if (StringUtils.isBlank(seRuleFile.getSeason())) {
                file = new File(upload + "/" + seRuleFile.getUrl());
            } else {
                file = new File(upload + "/" + seRuleFile.getSeason() + seRuleFile.getUrl());
            }

            List<RuleExcelDev> ruleExcelDevList;
            //如果文件损坏跳出
            try {
                ruleExcelDevList = obj.readNormExcel(file);
            } catch (Exception e) {
                continue;
            }
            if (ruleExcelDevList == null || ruleExcelDevList.size() < 1) {

            } else {
                for (RuleExcelDev ruleExcelDev : ruleExcelDevList) {
//                if (seRuleFile.getSeason().equals("winter")) {
//                    ruleExcelDev.setSeason("冬季");
//                } else {
//                    ruleExcelDev.setSeason("夏季");
//                }
//                RuleExcelUser reu = obj.tranRuleExcelOut(ruleExcelDev);
                    //直接存
                    ruleExcelUserList.add(obj.tranRuleExcelOut(ruleExcelDev));


                }
                ruleExcelUser.setId(seRuleFile.getId());
                ruleExcelUser.setRuleExcelUserList(ruleExcelUserList);
                ruleExcelUser.setWhetherUse(seRuleFile.getWhetherUse());
                ruleExcelUsers.add(ruleExcelUser);
            }
        }

        return ruleExcelUsers;
    }

    /*
     * 判断集合是否属于一个监控变量  是就放到一起   去重
     * */
    public List<RuleExcelUser> merge(List<RuleExcelUser> ruleExcelUsers) {
        //根据pointname 判断是否合到一起  用来判断 是否相同
        HashMap<String, List<RuleExcelUser>> tempMap = new HashMap<>();
        //存最终数据
        HashMap<String, RuleExcelUser> tempMap1 = new HashMap<>();

        for (RuleExcelUser excelUser : ruleExcelUsers) {
            String temp = excelUser.getUrl();
            //包含
            if (tempMap.containsKey(temp)) {
                RuleExcelUser ruleExcelUser2 = new RuleExcelUser();
                ruleExcelUser2.setUrl(temp);

                ruleExcelUser2.setId(excelUser.getId());
                ruleExcelUser2.setPointName(excelUser.getPointName());
                // ruleExcelUser2.setPointName(excelUser.getPointName());
                //  ruleExcelUser2.setDroolsname(excelUser.getDroolsname());
                //标准
                ruleExcelUser2.setStandard(excelUser.getStandard());
                ruleExcelUser2.setModelId(excelUser.getModelId());
                // List<RuleExcelUser> ruleExcelUsers3 = new ArrayList<>();
                ruleExcelUser2.setRuleExcelUserList(excelUser.getRuleExcelUserList());
                ruleExcelUser2.setWhetherUse(excelUser.getWhetherUse());
                ruleExcelUser2.setAlarmType(excelUser.getAlarmType());
                ruleExcelUser2.setWhethermatches(excelUser.getWhethermatches());
                ruleExcelUser2.setDbId(excelUser.getDbId());
                ruleExcelUser2.setRoomType(excelUser.getRoomType());


                ruleExcelUser2.setMonitorType(excelUser.getMonitorType());
                List<RuleExcelUser> ruleExcelUserList = ruleExcelUser2.getRuleExcelUserList();
                List<RuleExcelUser> ruleExcelUsers4 = tempMap.get(temp);
                //用来判断 变量是否相同
                if (!ruleExcelUserList.equals(ruleExcelUsers4)) {
                    for (RuleExcelUser ruleExcelUser : ruleExcelUsers4) {
                        if (!ruleExcelUserList.contains(ruleExcelUser)) {
                            ruleExcelUser2.getRuleExcelUserList().add(ruleExcelUser);
                        }
                    }
                } else {
                }

                tempMap.put(temp, ruleExcelUser2.getRuleExcelUserList());
                tempMap1.put(temp, ruleExcelUser2);
                // ruleExcelUser2.setRuleExcelUserList(stringRuleExcelUserHashMap.get(ponint).getRuleExcelUserList()+excelUser.getRuleExcelUserList());
            } else {
                tempMap.put(temp, excelUser.getRuleExcelUserList());
                tempMap1.put(temp, excelUser);
            }

        }
        ArrayList<RuleExcelUser> ruleExcelUserArrayList = new ArrayList<>();

        for (String s : tempMap1.keySet()) {
            ruleExcelUserArrayList.add(tempMap1.get(s));
        }

        //升序
        ruleExcelUserArrayList.sort(Comparator.comparing(RuleExcelUser::getId));
        return ruleExcelUserArrayList;
    }

    @ApiOperation(value = "修改规则", notes = "测试用接口", httpMethod = "POST")
    @PostMapping(value = "/updatedrools")
    public Result updatedrools(@RequestBody RuleExcelUser ruleExcelUser) throws IOException, ParseException {
        if (ruleExcelUser.getWhethermatches().equals("类型")) {
            ruleExcelUser.setPointName(ruleExcelUser.getPointName().split(" ")[0]);
        }


        List<SeRuleFile> selectbyid = fileMapper.selectbyid(ruleExcelUser.getId());
        for (SeRuleFile seRuleFile : selectbyid) {
            File file = null;
            //保养没有季节
            if (StringUtils.isBlank(seRuleFile.getSeason())) {
                file = new File(upload + seRuleFile.getUrl());

            } else {
                file = new File(upload + "/" + seRuleFile.getSeason() + seRuleFile.getUrl());
            }

            //File file = new File("D:/drools.xls");
            boolean exists = file.exists();
            int delectbydroolsname = fileMapper.delectbyfilename(seRuleFile.getFilename(), seRuleFile.getAlarmType());

            //文件读取

            if (exists) {
                boolean delete = file.delete();
                System.out.println(delete);
            } else {
                return Result.error().message("文件不存在");
            }
        }
        int write = write(ruleExcelUser);

        this.run();

        return Result.ok();
    }


    @ApiOperation(value = "添加规则", notes = "测试用接口", httpMethod = "POST")
    @PostMapping(value = "/insertdrools")
    public Result insertdrools(@RequestBody RuleExcelUser ruleExcelUser) throws IOException, ParseException {
//        Date date = new Date();

        if (ruleExcelUser.getWhethermatches().equals("类型")) {
            ruleExcelUser.setPointName(ruleExcelUser.getPointName().split(" ")[0]);
        }
        List<SeRuleFile> selectbydroolsname = fileMapper.selectbyfilename(ruleExcelUser.getPointName(), ruleExcelUser.getAlarmType());
        if (selectbydroolsname.size() == 0) {
            //写入规则
            int write = write(ruleExcelUser);
            //文件读取
            this.run();

            return Result.ok();
        } else {
            for (SeRuleFile seRuleFile : selectbydroolsname) {
                File file = null;
                //保养没有季节
                if (StringUtils.isBlank(seRuleFile.getSeason())) {
                    file = new File(upload + seRuleFile.getUrl());

                } else {
                    file = new File(upload + "/" + seRuleFile.getSeason() + seRuleFile.getUrl());
                }

                //File file = new File("D:/drools.xls");
                boolean exists = file.exists();
                int delectbydroolsname = fileMapper.delectbyfilename(seRuleFile.getFilename(), seRuleFile.getAlarmType());

                //文件读取

                if (exists) {
                    boolean delete = file.delete();
                    System.out.println(delete);
                }
            }
            int write = write(ruleExcelUser);
            this.run();
            return Result.ok().message("已有此监控对象,修改成功");
        }


    }

    //    public  int write(RuleExcelUser ruleExcelUser){
//
//        String[] pointNamesplit = ruleExcelUser.getPointName().split(";");
//        String[] dbIdsplit = ruleExcelUser.getDbId().split(";");
//        int  a=0;
//        int insertdrools=0;
//        for (String pointName : pointNamesplit) {
//
//
//
//
//        ReadExcelRuleEngine obj = new ReadExcelRuleEngine();
//        List<RuleExcelUser> summer = new ArrayList<>();
//        List<RuleExcelUser> winter = new ArrayList<>();
//        List<RuleExcelUser> Maintain = new ArrayList<>();
//        SeRuleFile seRuleFile = new SeRuleFile();
//        for (RuleExcelUser r : ruleExcelUser.getRuleExcelUserList()) {
//            if (StringUtils.isBlank(r.getSeason())){
//                if (r.getVariableName().equals("寿命到期")){ //
//                    seRuleFile.setLifedata(r.getVariable());}
//                Maintain.add(r);
//            }else
//            if (r.getSeason().equals("夏季")) {
//                summer.add(r);
//            } else if (r.getSeason().equals("冬季")) {
//                winter.add(r);
//            } else if (r.getSeason().equals("四季")) {
//                summer.add(r);
//                winter.add(r);
//            }
//
//            else {//防止用户瞎几把写,预留,后期可以根据操作时间,全部写成当季
//
//            }
//        }
//        //获取标准 监控对象 拼接为文件名
//        //String filename = upload + ruleExcelUser.getPointName() + "&&" + ruleExcelUser.getStandard() + ".xls";
//        //将数据添加到execl  文件绝对路径    是否包含    规则名   变量    监控对象
//
//
//        seRuleFile.setFilename(pointName);
//        seRuleFile.setUrl("/" + pointName+ruleExcelUser.getAlarmType()+ ".xls");
//        seRuleFile.setWhetherUse(1);
//        seRuleFile.setStandard(ruleExcelUser.getStandard());
//       // seRuleFile.setDroolsname(ruleExcelUser.getDroolsname());
//        seRuleFile.setMonitorType(ruleExcelUser.getMonitorType());
//        seRuleFile.setModelId(ruleExcelUser.getModelId());
//        seRuleFile.setWhethermatches(ruleExcelUser.getWhethermatches());
//        seRuleFile.setAlarmType(ruleExcelUser.getAlarmType());
//        seRuleFile.setDbid(Integer.parseInt(dbIdsplit[a]));
//        seRuleFile.setRoomType(ruleExcelUser.getRoomType());
//
//        if (summer.size() > 0) {//有夏季,写夏季
//            String filename = upload + "summer/" + pointName +ruleExcelUser.getAlarmType()+ ".xls";
//            obj.writeExcel(filename, ruleExcelUser.whethermatches,ruleExcelUser.getStandard(), pointName, summer, pointName, "summer");
//
//            seRuleFile.setSeason("summer");
//            //存储路径
//             insertdrools = fileMapper.insertdrools(seRuleFile);
//
//        }
//        if (winter.size() > 0) {//有冬季,写冬季
//            String filename = upload + "winter/" + pointName+ruleExcelUser.getAlarmType()+ ".xls";
//            obj.writeExcel(filename, ruleExcelUser.whethermatches,ruleExcelUser.getStandard(), pointName, winter, pointName, "winter");
//
//            seRuleFile.setSeason("winter");
//            //存储路径
//             insertdrools = fileMapper.insertdrools(seRuleFile);
//        }
//        //obj.writeExcel(filename, ruleExcelUser.whethermatches, ruleExcelUser.getPointName(), ruleExcelUser.getRuleExcelUserList(), ruleExcelUser.getPointName());
//
//        if (Maintain.size() > 0) {//保养 没季节
//            //将数据添加到execl  文件绝对路径    是否包含    规则名   变量    监控对象
//            String filename = upload + pointName +ruleExcelUser.getAlarmType() + ".xls";
//            obj.writeExcel(filename, ruleExcelUser.whethermatches,ruleExcelUser.getStandard(), pointName, Maintain, pointName, " ");
//            seRuleFile.setSeason(" ");
//            //存储路径
//             insertdrools = fileMapper.insertdrools(seRuleFile);
//        }
//            insertdrools=insertdrools+insertdrools;
//        }
//        return  insertdrools;
//    }
    public int write(RuleExcelUser ruleExcelUser) {
        ReadExcelRuleEngine obj = new ReadExcelRuleEngine();
        List<RuleExcelUser> summer = new ArrayList<>();
        List<RuleExcelUser> winter = new ArrayList<>();
        List<RuleExcelUser> Maintain = new ArrayList<>();
        SeRuleFile seRuleFile = new SeRuleFile();
        for (RuleExcelUser r : ruleExcelUser.getRuleExcelUserList()) {
            if (StringUtils.isBlank(r.getSeason())) {
                if (r.getVariableName().equals("寿命到期")) { //
                    seRuleFile.setLifedata(r.getVariable());
                } else if (r.getVariableName().equals("保修到期")) {
                    seRuleFile.setMaintenancedata(r.getVariable());
                }
                Maintain.add(r);
            } else if (r.getSeason().equals("夏季")) {
                summer.add(r);
            } else if (r.getSeason().equals("冬季")) {
                winter.add(r);
            } else if (r.getSeason().equals("四季")) {
                summer.add(r);
                winter.add(r);
            } else {//防止用户瞎几把写,预留,后期可以根据操作时间,全部写成当季

            }
        }
        //获取标准 监控对象 拼接为文件名
        //String filename = upload + ruleExcelUser.getPointName() + "&&" + ruleExcelUser.getStandard() + ".xls";
        //将数据添加到execl  文件绝对路径    是否包含    规则名   变量    监控对象


        seRuleFile.setFilename(ruleExcelUser.getPointName());
        seRuleFile.setUrl("/" + ruleExcelUser.getPointName() + ruleExcelUser.getAlarmType() + ".xls");
        seRuleFile.setWhetherUse(1);
        seRuleFile.setStandard(ruleExcelUser.getStandard());
        // seRuleFile.setDroolsname(ruleExcelUser.getDroolsname());
        seRuleFile.setMonitorType(ruleExcelUser.getMonitorType());
        seRuleFile.setModelId(ruleExcelUser.getModelId());
        seRuleFile.setWhethermatches(ruleExcelUser.getWhethermatches());
        seRuleFile.setAlarmType(ruleExcelUser.getAlarmType());
        seRuleFile.setDbid(ruleExcelUser.getDbId());
        seRuleFile.setRoomType(ruleExcelUser.getRoomType());
        int insertdrools = 0;
        if (summer.size() > 0) {//有夏季,写夏季
            String filename = upload + "summer/" + ruleExcelUser.getPointName() + ruleExcelUser.getAlarmType() + ".xls";
            obj.writeExcel(filename, ruleExcelUser.whethermatches, ruleExcelUser.getStandard(), ruleExcelUser.getPointName(), summer, ruleExcelUser.getPointName(), "summer");

            seRuleFile.setSeason("summer");
            //存储路径
            insertdrools = fileMapper.insertdrools(seRuleFile);

        }
        if (winter.size() > 0) {//有冬季,写冬季
            String filename = upload + "winter/" + ruleExcelUser.getPointName() + ruleExcelUser.getAlarmType() + ".xls";
            obj.writeExcel(filename, ruleExcelUser.whethermatches, ruleExcelUser.getStandard(), ruleExcelUser.getPointName(), winter, ruleExcelUser.getPointName(), "winter");

            seRuleFile.setSeason("winter");
            //存储路径
            insertdrools = fileMapper.insertdrools(seRuleFile);
        }
        //obj.writeExcel(filename, ruleExcelUser.whethermatches, ruleExcelUser.getPointName(), ruleExcelUser.getRuleExcelUserList(), ruleExcelUser.getPointName());

        if (Maintain.size() > 0) {//保养 没季节
            //将数据添加到execl  文件绝对路径    是否包含    规则名   变量    监控对象
            String filename = upload + ruleExcelUser.getPointName() + ruleExcelUser.getAlarmType() + ".xls";
            obj.writeExcel(filename, ruleExcelUser.whethermatches, ruleExcelUser.getStandard(), ruleExcelUser.getPointName(), Maintain, ruleExcelUser.getPointName(), " ");
            seRuleFile.setSeason(" ");
            //存储路径
            insertdrools = fileMapper.insertdrools(seRuleFile);
        }
        return insertdrools;
    }


    @ApiOperation(value = "删除规则", notes = "测试用接口", httpMethod = "POST")
    @PostMapping(value = "/delectdrools")
    public Result delectdrools(@RequestParam("filename") String filename, @RequestParam("standard") String standard, @RequestParam("alarmType") String alarmType) throws ParseException {
        //先暂时麻烦点 后续在改


        List<SeRuleFile> selectbydroolsname = fileMapper.selectbyfilename(filename, alarmType);

        List<msgDevice> msgDeviceList = null;

        if (selectbydroolsname.get(0).getWhethermatches().equals("类型")) {
            msgDeviceList = alarmMapper.selectbyname(selectbydroolsname.get(0).getFilename());
        } else {
            msgDeviceList = alarmMapper.selectbydbidandmodelidlist(selectbydroolsname.get(0).getDbid(), String.valueOf(selectbydroolsname.get(0).getModelId()));
        }
        for (msgDevice msgDevice : msgDeviceList) {
            alarmMapper.delectbyid(msgDevice.getId());
            alarmMapper.delectmessageRemindbyid(msgDevice.getId());
        }
        if (selectbydroolsname.get(0).getAlarmType().equals("保养") && selectbydroolsname.get(0).getWhethermatches().equals("实例")) {
            alarmMapper.delectomdroolsdbyid(selectbydroolsname.get(0).getDbid());
        } else if (selectbydroolsname.get(0).getAlarmType().equals("保养") && selectbydroolsname.get(0).getWhethermatches().equals("类型")) {
            alarmMapper.delectomdroolsdbyname(selectbydroolsname.get(0).getFilename());
        }

        for (SeRuleFile seRuleFile : selectbydroolsname) {
            File file = null;
            //用来区分 保养 保养没有季节
            if (StringUtils.isBlank(seRuleFile.getSeason())) {
                file = new File(upload + seRuleFile.getUrl());
                int delectbyid = fileMapper.delectbyfilename(filename, alarmType);

            } else {
                file = new File(upload + "/" + seRuleFile.getSeason() + seRuleFile.getUrl());
                int delectbyid = fileMapper.delectbyfilename(filename, alarmType);
            }
            //File file = new File("D:/drools.xls");
            boolean exists = file.exists();

            //文件读取
            this.run();
            if (exists) {
                boolean delete = file.delete();
                System.out.println(delete);
            } else {
                return Result.error().message("文件不存在");
            }

        }
        return Result.ok().message("删除成功");
    }

    @ApiOperation(value = "是否使用规则", notes = "测试用接口", httpMethod = "POST")
    @PostMapping(value = "/wheathershow")
    public Result wheathershow(@RequestParam("filename") String filename, @RequestParam("standard") String standard, @RequestParam("whetherUse") int whetherUse, @RequestParam("alarmType") String alarmType) throws ParseException {
        int i = fileMapper.updatewhetherUse(filename, whetherUse, alarmType);
        //文件读取
        this.run();
        //  dataxbyuser();
        if (i > 0) {
            return Result.ok().message("设置成功");
        } else {
            return Result.error().message("设置失败");
        }


    }
//
//    List<fmDevInfo> selectbydevname = infoMapper.selectbydevname("名", "编号");
//        if (selectbydevname.size()!=0){
//
//    }
//    fmRoominfo selectbyroomname = infoMapper.selectbyroomname("名", "编号");
//        if (selectbyroomname!=null){
//
//    }
//
//
//    int insertdrools = fileMapper.insertdrools(seRuleFile);

    @ApiOperation(value = "查询绑定的设备", notes = " ", httpMethod = "POST")
    @PostMapping({"/getbindingdev"})
    public Result getbindingdev(@RequestParam String keyword) throws ParseException {
        List<fmDevTree> selectroot = new ArrayList<>();
        fmDevTree modelTree2 = new fmDevTree();
        modelTree2.setSName("通讯设备");
        selectroot.add(modelTree2);
        for (fmDevTree modelTree : selectroot) {
            modelTree.setLevel(1);
            List<String> Storey = pointEqipmentMapper.disStorey();
            ArrayList<fmDevTree> treeArrayList = new ArrayList<>();
            for (String s : Storey) {
                fmDevTree storeyModelTree = new fmDevTree();
                storeyModelTree.setSName(s);
                storeyModelTree.setLevel(2);
                treeArrayList.add(storeyModelTree);
            }
            //二级
            for (fmDevTree tree : treeArrayList) {
                ArrayList<fmDevTree> devmodelTree = new ArrayList<>();
                //如果楼层为空
                List<icDevPoint> pointEquipments = new ArrayList<>();
                if (StringUtils.isBlank(tree.getSName())) {
                    pointEquipments = pointEqipmentMapper.selectbyStoreyisnull(keyword);
                    tree.setSName("其他");
                } else {
                    pointEquipments = pointEqipmentMapper.selectbyStorey(tree.getSName(), keyword);
                }

                for (icDevPoint pointEquipment : pointEquipments) {
                    fmDevTree devmodel = new fmDevTree();
                    devmodel.setSName(pointEquipment.getDevName());
                    devmodel.setDevNumber(pointEquipment.getDevNumber());
                    devmodel.setModelId(pointEquipment.getModelId());
                    devmodel.setDbId(pointEquipment.getDbid());
                    devmodel.setLevel(3);
                    devmodelTree.add(devmodel);
                }
                tree.setChildren(devmodelTree);

            }
            modelTree.setChildren(treeArrayList);
        }
        for (fmDevTree modelTree : selectroot) {
            Iterator<fmDevTree> iterator1 = modelTree.getChildren().iterator();
            while (iterator1.hasNext()) {
                List<fmDevTree> children = ((fmDevTree) iterator1.next()).getChildren();
                if (children.size() == 0) iterator1.remove();
            }
        }
        Iterator<fmDevTree> iterator = selectroot.iterator();
        while (iterator.hasNext()) {
            List<fmDevTree> children = ((fmDevTree) iterator.next()).getChildren();
            if (children.size() == 0) iterator.remove();
        }
        return Result.success(selectroot);
    }

//    @ApiOperation(value = "查询绑定的设备", notes =" ", httpMethod = "POST")
//    @PostMapping({"/getbindingdev"})
//    public Result getbindingdev(@RequestParam String keyword) throws ParseException {
//        List<fmDevTree> selectroot =infoMapper.selectroot();
//        for (fmDevTree modelTree : selectroot) {
//            modelTree.setLevel(1);
//            List<fmDevTree> modelTrees =infoMapper.selectbyPid(modelTree.getId());
//            for (fmDevTree tree : modelTrees) {
//                tree.setLevel(2);
//                ArrayList<fmDevTree> treeArrayList = new ArrayList<>();
//                List<icDevPoint> pointEquipments =pointEqipmentMapper.selectbySt1St2(modelTree.getSName(), tree.getSName(), keyword);
//                for (icDevPoint pointEquipment : pointEquipments) {
//                    fmDevTree modelTree1 = new fmDevTree();
//                    modelTree1.setDbId(pointEquipment.getDbid());
//                    modelTree1.setLevel(3);
//                    modelTree1.setSName(pointEquipment.getDeviceName() + " " + pointEquipment.getDevNumber());
//                    modelTree1.setModelId(pointEquipment.getModelId());
//                    treeArrayList.add(modelTree1);
//                }
//                tree.setChildren(treeArrayList);
//            }
//            modelTree.setChildren(modelTrees);
//        }
//        for (fmDevTree modelTree : selectroot) {
//            Iterator<fmDevTree> iterator1 = modelTree.getChildren().iterator();
//            while (iterator1.hasNext()) {
//                List<fmDevTree> children = ((fmDevTree)iterator1.next()).getChildren();
//                if (children.size() == 0)
//                    iterator1.remove();
//            }
//        }
//        Iterator<fmDevTree> iterator = selectroot.iterator();
//        while (iterator.hasNext()) {
//            List<fmDevTree> children = ((fmDevTree)iterator.next()).getChildren();
//            if (children.size() == 0)
//                iterator.remove();
//        }
//        return Result.success(selectroot);
//    }

    @ApiOperation(value = "查询绑定的房间", notes = " ", httpMethod = "POST")
    @PostMapping({"/getbindingroom"})
    public Result getbindingroom(@RequestParam("keyword") String keyword) throws ParseException {
        //查询所属房间的设备
        List<icDevPoint> selectdevbyenvironment = pointEqipmentMapper.selectdevbyenvironment();
        ArrayList<fmRoominfo> fmRoominfos = new ArrayList<>();
        for (icDevPoint pointEquipment : selectdevbyenvironment) {
            fmRoominfo fmRoominfo = infoMapper.selectfloorbydeviceName(pointEquipment.getDbid(), pointEquipment.getModelId());
            if ((fmRoominfos.size() == 0 || !fmRoominfos.contains(fmRoominfo)) && fmRoominfo != null) {
                if (StringUtils.isNoneBlank(keyword) && fmRoominfo.getRmName().contains(keyword)) {
                    fmRoominfos.add(fmRoominfo);
                } else {
                    fmRoominfos.add(fmRoominfo);
                }

            }
        }
        List<fmRoomTree> selectroot = infoMapper.selectrootbyRoom();
        for (fmRoomTree FloorTree : selectroot) {
            FloorTree.setLevel(1);
            List<fmRoomTree> floorTrees = infoMapper.selectRoombyPid(FloorTree.getId());
            for (fmRoomTree tree : floorTrees) {
                tree.setLevel(2);
                tree.setTitle(tree.getSName());
                ArrayList<fmRoomTree> treeArrayList = new ArrayList<>();

                for (fmRoominfo fmRoominfo : fmRoominfos) {

                    if (StringUtils.isNotBlank(fmRoominfo.getRmLevel()) && fmRoominfo.getRmLevel().equals(tree.getSName())) {
                        fmRoomTree floorTree = new fmRoomTree();
                        floorTree.setDbId(Integer.parseInt(fmRoominfo.getObjectId()));
                        floorTree.setLevel(3);
                        floorTree.setSName(fmRoominfo.getRmName());
                        floorTree.setTitle(fmRoominfo.getRmName());
                        floorTree.setHouseNumber(fmRoominfo.getHouseNumber());
                        floorTree.setModelId(fmRoominfo.getModelId());
                        floorTree.setRmNumber(fmRoominfo.getRmNumber());
                        treeArrayList.add(floorTree);
                    }
                }
                tree.setChildren(treeArrayList);
            }
            FloorTree.setChildren(floorTrees);
        }
        for (fmRoomTree floorTree : selectroot) {
            Iterator<fmRoomTree> iterator1 = floorTree.getChildren().iterator();
            while (iterator1.hasNext()) {
                List<fmRoomTree> children = ((fmRoomTree) iterator1.next()).getChildren();
                if (children.size() == 0) iterator1.remove();
            }
        }
        Iterator<fmRoomTree> iterator = selectroot.iterator();
        while (iterator.hasNext()) {
            List<fmRoomTree> children = ((fmRoomTree) iterator.next()).getChildren();
            if (children.size() == 0) iterator.remove();
        }
        return Result.success(selectroot);
    }

    @ApiOperation(value = "是否使用规则", notes = "测试用接口", httpMethod = "POST")
    @PostMapping(value = "/Camera")
    public Result Camera(String dbId, String modelId) throws ParseException {
        List<Map<String, String>> camera = new ArrayList<>();
//        List<fmDevInfo> dbidbyfloor = pointEqipmentMapper.dbidbyfloor("22", "1");
//        for (fmDevInfo deviceinfo : dbidbyfloor) {
//            List<icDevPoint> selectbydbid = pointEqipmentMapper.selectbydbid(deviceinfo.getObjectId(), "1");
//            for (icDevPoint pointEquipment : selectbydbid) {
//                HashMap<String, String> map = new HashMap<>();
//                icMqttConf icConnect = pointEqipmentMapper.selectbyponit(pointEquipment.getPointid());
//                String  rtsp="rtsp://"+icConnect.getUserName()+":"+icConnect.getPassword()
//                        +"@"+pointEquipment.getPointName()+":"+icConnect.getCameraPort();
//                String  HTTP="http://"+icConnect.getServiceUrl()+":"+icConnect.getPort();
//
//                map.put("rtsp",rtsp);
//                // map.put("server","HTTP://192.168.31.29:8000");
//                map.put("server",HTTP);
//                camera.add(map);
//
//            }
//
//        }
        for (int i = 0; i < 4; i++) {
            HashMap<String, String> map = new HashMap<>();
            map.put("rtsp", "rtsp://admin:hik12345@192.168.31.120:554");
            // map.put("server","HTTP://192.168.31.29:8000");
            map.put("server", "HTTP://192.168.31.171:8000");
            camera.add(map);
        }
        WebSocketServerCamera.sendMessage(JSONArray.toJSONString(camera));
        return null;
    }

    @ApiOperation(value = "查询寿命到期时间", notes = "测试用接口", httpMethod = "POST")
    @PostMapping(value = "/selectlife")
    public Result selectlife(String dbId, String modelId) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        fmDevInfo fmDeviceinfo = infoMapper.selectdevicebyobjectId(dbId, modelId);
        if (fmDeviceinfo.getPurchaseDate() != null && StringUtils.isNotBlank(fmDeviceinfo.getPurchaseDate().toString()) && fmDeviceinfo.getDevLife() != null) {
            Calendar c = Calendar.getInstance();
            c.setTime(fmDeviceinfo.getPurchaseDate());
            //c.set
            c.add(Calendar.YEAR, fmDeviceinfo.getDevLife());
            return Result.success(sdf.format(c.getTime()));
        } else {
            return Result.success(null);
        }


    }


    @ApiOperation(value = "根据设备名房间名搜索绑定的变量", notes = "测试用接口", httpMethod = "POST")
    @PostMapping(value = "/selectvariname")
    public Result selectvarname(@RequestParam("sname") String sname, @RequestParam("modelId") String modelId) {
        //查询绑定表
        String[] s = sname.split(" ");
        //修改为查询别名
        List<String> devvari = pointEqipmentMapper.variDis(s[0], modelId);
        if (devvari.size() == 0) {
            ArrayList<String> vari = new ArrayList<>();
            // List<fmDevInfo> fmDeviceinfos = pointEqipmentMapper.deviceNamebyfloor(s[0], modelId);
            List<fmDevInfo> fmDeviceinfos =null;
            if (s.length==1){
                fmDeviceinfos = pointEqipmentMapper.deviceNamebyfloor(s[0], " ", modelId);
            }else {
                fmDeviceinfos = pointEqipmentMapper.deviceNamebyfloor(s[0], s[1], modelId);
            }
            for (fmDevInfo fmDeviceinfo : fmDeviceinfos) {
                //修改为查询别名
                List<String> variname = pointEqipmentMapper.aliasDisbydbid(fmDeviceinfo.getObjectId(), fmDeviceinfo.getModelId());
                if (variname.size()==0){
                    variname = pointEqipmentMapper.variDisbydbid(fmDeviceinfo.getObjectId(), fmDeviceinfo.getModelId());
                }
                vari.addAll(variname);
            }
            Set set = new HashSet();
            set.addAll(vari);
            vari.clear();
            vari.addAll(set);
            for (int i = 0; i < vari.size(); i++) {
                if (StringUtils.isBlank(vari.get(i))) {
                    vari.remove(i);
                }
            }
            return Result.success(vari);
        } else {
            for (int i = 0; i < devvari.size(); i++) {
                if (StringUtils.isBlank(devvari.get(i))) {
                    devvari.remove(i);
                }
            }
            return Result.success(devvari);
        }
    }


}
